"use strict";
import axios from "axios";
import qs from "qs"; // 解析json库
import globalData from "@/config"; // 基础信息
// import {
// 	post_refresh
// } from '@/api/index.js'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post["Content-Type"] =
// "application/x-www-form-urlencoded;charset=UTF-8";
const config = {
	baseURL: globalData.http_host, //请求域名
	timeout: 8000, // 超时时间,
	withCredentials: true, // Check cross-site Access-Control
	crossDomain: true,
	withCredentials: true,
	async: false, //true为会缓存，false取消缓存；true时从A页面到B页面，A页面的请求会缓存下来，当从B页面回到A页面时，A页面是旧数据
};

// axios 请求
const request = axios.create(config);

// 是否正在刷新的标记
let isRefreshing = false
//存储过期的请求
let expiredList = []

/**
 * @Author: liuxu
 * @description: axios 初始化请求参数
 * @param {Object} config
 * @return {*}
 */
const requestData = function(config) {
	let requestData = {};
	try {
		// #ifdef MP-WEIXIN
		requestData.mini_user_token = mini_user_token;
		// #endif
	} catch (e) {
		// console.log("index.js请求参数:", e)
	}
	return {
		...config.data,
		...requestData,
	};
};

// 队列相关逻辑
const queue = [];
const cancelToken = axios.CancelToken;
const token = (config) => `${config.url}_${config.method}`;
const removeQueue = (config) => {
	// 如果是刷新请求，直接跳过，不处理
	if (config.isRefreshRequest) return;

	for (let i = 0, size = queue.length; i < size; i++) {
		const task = queue[i];
		if (task && task.token === token(config)) {
			task.cancel();
			queue.splice(i, 1);
		}
	}
};

// 请求拦截器
request.interceptors.request.use(
	(config) => {
		// 跳过重复检测，若是刷新token请求
		removeQueue(config);

		// 显示Loading
		config.loading !== false &&
			uni.showLoading({
				title: "加载中",
				mask: true,
			});
		// 取消token处理
		config.cancelToken = new cancelToken((c) => {
			if (config.method.toUpperCase() === "GET") {
				config.params = {
					...config.params,
					...requestData(config)
				};
			} else {
				config.data = {
					...config.data,
					...requestData(config)
				};
			}
			queue.push({
				token: token(config),
				cancel: c,
			});
		});

		// 调试输出
		// console.info("request拦截器之前:", config);
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);
//配置成功后的拦截器
request.interceptors.response.use((response) => {
	try {
		response.config.loading !== false && uni.hideLoading();
		if (response.status === 200 && response.data.code === 200) {
			return response.data;
		} else if (response.data.code === 401) {
			uni.clearStorageSync('token')
			// uni.showToast({
			// 	title: '未登录',
			// 	icon: 'none'
			// })
			uni.reLaunch({
				url: '/pages/login/index'
			})
			return response.data;
			// if (!isRefreshing) {
			// 	isRefreshing = true;

			// 	return post_refresh({
			// 		refresh_token: uni.getStorageSync('refresh_token')
			// 	}).then(result => {
			// 		uni.setStorageSync('token', result.data.access_token);
			// 		uni.setStorageSync('refresh_token', result.data.refresh_token);

			// 		expiredList.forEach(callback => callback(result.data.access_token));
			// 		expiredList = [];

			// 		const newConfig = {
			// 			...response.config
			// 		};
			// 		newConfig.headers.Authorization = `${result.data.access_token}`;

			// 		// 修正序列化逻辑
			// 		newConfig.paramsSerializer = (params) => {
			// 			return qs.stringify(params, {
			// 				arrayFormat: 'brackets'
			// 			});
			// 		};

			// 		return request(newConfig);
			// 	}).catch(err => {
			// 		uni.removeStorageSync('token');
			// 		uni.removeStorageSync('refresh_token');
			// 		return Promise.reject(err);
			// 	}).finally(() => {
			// 		isRefreshing = false;
			// 	});
			// } else {
			// 	return new Promise((resolve) => {
			// 		expiredList.push((newToken) => {
			// 			const newConfig = {
			// 				...response.config
			// 			};
			// 			newConfig.headers.Authorization = `${newToken}`;

			// 			// 防止重复拼接问题
			// 			if (newConfig.method.toUpperCase() === "GET") {
			// 				newConfig.params = response.config.params || {};
			// 			}

			// 			resolve(request(newConfig));
			// 		});
			// 	});
			// }
		} else {
			if (response.config.toastLoading) {
				uni.showToast({
					icon: 'none',
					title: response.data.message
				})
			}
			return response.data;
		}
	} catch (e) {
		return Promise.reject({
			response
		});
	}
});

// 生成 URL
function buildURL(url, params, paramsSerializer) {
	if (!params) return url;
	const serializedParams = paramsSerializer ?
		paramsSerializer(params) :
		qs.stringify(params, {
			arrayFormat: 'brackets'
		});
	return url + (url.includes('?') ? '&' : '?') + serializedParams;
}

// 自己实现 settle 逻辑
function settle(resolve, reject, response) {
	const validateStatus = response.config.validateStatus || function(status) {
		return status >= 200 && status < 300;
	};
	if (validateStatus(response.status)) {
		resolve(response);
	} else {
		const error = new Error('Request failed with status code ' + response.status);
		Object.assign(error, {
			config: response.config,
			response
		});
		reject(error);
	}
}


request.defaults.adapter = function(config) {
	//自己定义个适配器，用来适配uniapp的语法
	return new Promise((resolve, reject) => {
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: {
				"Content-Type": "application/json; charset=UTF-8",
				"xm-token": uni.getStorageSync('token') || ''
			},
			timeout: config.timeout,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			withCredentials: true,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config,
				};
				settle(resolve, reject, response);
			}
		});
	});
};

export default request;